﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;

namespace HexunMicrobloggingClientUI
{
    public class Logger
    {
        static public Logger GetLogger()
        {
            return m_objLogger;
        }

        private string logPath = System.Windows.Forms.Application.StartupPath + "\\Logs";

        private static bool isOutputDebugInfo = IsOutputDebugInfo();

        public void SetPrefix(string strPrefix)
        {
            m_strPrefix = strPrefix;
        }

        public void Debug(Exception e)
        {
            try
            {
                Debug(e.Message, e);
            }
            catch
            {
            }
        }

        public void Error(Exception e)
        {
            try
            {
                Error(e.Message, e);
            }
            catch
            {
            }
        }

        public void Debug(string strMsg)
        {
            try
            {
                Debug(strMsg, null);
            }
            catch
            {
            }
        }

        public void Error(string strMsg)
        {
            try
            {
                Error(strMsg, null);
            }
            catch
            {
            }
        }

        public void Debug(string strDebug, Exception e)
        {
            if (!isOutputDebugInfo)
            {
                return;
            }

            try
            {
                StringWriter objWriter = new StringWriter();
                objWriter.Write("\r\n[Debug] " + GetTime() + "\r\n");
                objWriter.Write(strDebug + "\r\n");
                Write2File(objWriter.ToString(), e);
            }
            catch
            {
            }
        }


        public string LogPath
        {
            get
            {
                return logPath;
            }

            set
            {
                logPath = value;
            }
        }


        public void Error(string strError, Exception e)
        {
            try
            {
                StringWriter objWriter = new StringWriter();
                objWriter.Write("\r\n[Error] " + GetTime() + "\r\n");
                objWriter.Write(strError + "\r\n");
                Write2File(objWriter.ToString(), e);
            }
            catch
            {
            }
        }

        private static bool IsOutputDebugInfo()
        {
            string configFile = System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name.Replace(".dll", ".config").Replace(".exe", ".config");
            try
            {
                XElement root = XElement.Load(configFile);
                var userData = from el in root.Elements("systemSettings").Elements("log").Elements("outputDebugInfo")
                               select el;
                XElement elUserData = userData.ElementAt(0);

                return bool.Parse(elUserData.Value.ToLower());
            }
            catch
            {
            }

            return false;
        }

        private void Write2File(string strMsg, Exception e)
        {
            try
            {
                if (!Directory.Exists(LogPath))
                {
                    Directory.CreateDirectory(LogPath);
                }
            }
            catch
            {
                return;
            }

            try
            {
                string strLogFileName = m_strPrefix + DateTime.Now.ToString("yyyy_MM_dd") + ".log";
                FileStream objOut = new FileStream(LogPath + "\\" + strLogFileName, FileMode.Append, FileAccess.Write);
                long len = objOut.Length;
                try
                {
                    objOut.Lock(0, len);
                    Encoding encode = System.Text.Encoding.GetEncoding("gb2312");
                    objOut.Write(encode.GetBytes(strMsg), 0, encode.GetByteCount(strMsg));
                    if (e != null)
                    {
                        string info = e.StackTrace;
                        if (info != null)
                        {
                            info += "\r\n";
                            objOut.Write(encode.GetBytes(info), 0, encode.GetByteCount(info));
                        }
                    }
                    objOut.Flush();
                }
                catch
                {
                }
                objOut.Unlock(0, len);
                objOut.Close();
            }
            catch
            {
            }
        }

        private string GetTime()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private static Logger m_objLogger = new Logger();
        private string m_strPrefix = "";
    }
}
